package com.lzx.iteam.net;

import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.ApprovalGroupData;
import com.lzx.iteam.bean.AttendanceClassData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Megan on 16/4/11.
 */
public class GetApprovalList extends CcMsgStructure {

    private static final String TAG = "GetAttendanceList";

    private Message mmCallback;

    public GetApprovalList(Message callback) {
        mmCallback = callback;
    }

    @Override
    public void onReceive(JSONObject data) {
        ArrayList<ApprovalGroupData> groups = new ArrayList<ApprovalGroupData>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            JSONArray jsonArray = jsonObject.getJSONArray("groups");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                ApprovalGroupData group = new ApprovalGroupData();
                group.setGroup_id(obj.getString("group_id"));
                group.setGroup_name(obj.getString("group_name"));
                group.setTodo_count(obj.getInt("todo_count"));
                groups.add(group);

            }
        } catch (JSONException e) {
            Log.e("My_JSONException",e.toString());
        }
        if (mmCallback != null)
        {
            mmCallback.obj = groups;
            mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
            return;
        }

    }

    @Override
    public void onError(int error, Object ret) {
        Log.d(TAG, "onError : " + error + " ret: " + ret);
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }

    }
}